import { Component, ChangeDetectionStrategy, Input, NgZone, ChangeDetectorRef } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd';

/**
 * 维修渠道饼图
 */
@Component({
  selector: 'prod-repair-channel',
  templateUrl: './repair-channel.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    '[class.card]': 'true',
  },
})
export class RepairChannelPieComponent {
  @Input()
  title = '';
  _codeName = null;
  @Input()
  set codeName(val) {
    if (val) {
      this._codeName = val;
      this.attachData(this._codeName);
    }
  }
  loading = false;
  total = 0;
  data = [];
  time = null;

  constructor(
    public http: _HttpClient,
    public msg: NzMessageService,
    private ngZone: NgZone,
    private cdr: ChangeDetectorRef,
  ) {}

  private attachData(codeName) {
    const { ngZone } = this;
    ngZone.run(() => {
      this.total = 0;
      this.data = [];
      this.loading = true;
      this.cdr.detectChanges();
    });
    this.http.get(`/cf/report/prod/repairchannel/${codeName}`).subscribe(res => {
      ngZone.run(() => {
        this.time = new Date();
        this.total = res.data.reduce((p, c) => (p += c.COUNT), 0);
        this.data = res.data.map(r => {
          return { x: this.parseName(r.CHANNEL), y: r.COUNT };
        });
        this.loading = false;
        this.cdr.detectChanges();
      });
    });
  }

  private parseName(n) {
    if (n === 'pf') {
      return '批发';
    }
    if (n === 'ls') {
      return '零售';
    }
    if (n === 'ds') {
      return '电商';
    }
    return '其它';
  }

  format(val: number) {
    return `${val}`;
  }
}
